﻿using Max.PH5_2011A.Domain;
using Max.PH5_2011A.IRespository;
using Max.PH5_2011A.IService;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Max.PH5_2011A.Service
{
    public class MemberAddressService : BaseService<MemberAddressModel>, IMemberAddressService
    {
        IMemberAddressRespository _respository;
        IUnitOfWork _unitOfWork;
        public MemberAddressService(IMemberAddressRespository respository, IUnitOfWork unitOfWork) : base(respository, unitOfWork)
        {
            _respository = respository;
            _unitOfWork = unitOfWork;
        }


        public int InsertAddress(MemberAddressModel model)
        {
            //开启事务
            using var _tran = _unitOfWork.GetDbConext().Database.BeginTransaction();
            try
            {
                //当被添加的这个地址，是设置为默认地址时，需要将其实的默认地址修改为非默认地址
                if (model.IsDefault)
                {
                    var list = _respository.Query().Where(x => x.MemberId == model.MemberId && x.IsDefault == true);
                    if (list != null && list.Count() > 0)
                    {
                        list.ToList().ForEach(x =>
                        {
                            x.IsDefault = false;
                            x.UpdatedTime = System.DateTime.Now;
                            _respository.Update(x);
                        });
                    }
                }
                //再添加
                _respository.Insert(model);

                //提交数据
                _unitOfWork.SaveChanges();

                //提交事务
                _tran.Commit();

                return 1;
            }
            catch (Exception)
            {
                //回滚事务
                _tran.Rollback();

                return -1;
            }


        }
    }
}
